<template>
  <div class="container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="月份">
        <el-date-picker size="small" @change="handleChangeData" value-format="yyyy-MM" v-model="formInline.date"
          type="month" placeholder="选择月"></el-date-picker>
        <!--   <el-input v-model="formInline.user" placeholder="时间"></el-input> -->
      </el-form-item>
      <el-form-item label="科室">
        <el-select size="small" @change="getDoctorScheduleList" v-model="formInline.sub_department_id" clearable
          filterable placeholder="请选择">
          <el-option v-for="item in subDepartMentArr" :key="item.name" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>

      </el-form-item>
      <el-form-item>
      </el-form-item>
    </el-form>
    <el-row style="margin-bottom: 25px;">
      <el-button type="primary" size="small" @click="getDoctorScheduleList">查询</el-button>
<!--       <el-button type="success" size="small" @click="importData">导入排版数据</el-button> -->
    </el-row>

    <!-- 查询结果 -->
    <div class="newTable">
      <div class="newTableCss">
        <el-table v-loading="tableLoading" :data="dataList" border style="width: 100%" @cell-click="handleCellClick"
          :key="indexData">
          <el-table-column prop="name" align="center" label="姓名" fixed>
          </el-table-column>
          <el-table-column v-for="(item,index) in monthData" align="center" width="120" :key="index" :prop="item.date">
            <template slot="header">
              <div>{{item.date}}</div>
              <div>{{item.day}}</div>
            </template>
            <template slot-scope="scope">
              <div v-if="scope.row[item.date]">
                <!--     <el-popover placement="top-start" title="问诊时间" width="200" trigger="hover"
                  :content="scope.row[item.date]"> -->
                <el-button type="danger" slot="reference">{{ forMatterDate(scope.row[item.date]) }}</el-button>
                <!--        </el-popover> -->
              </div>

            </template>
          </el-table-column>
        </el-table>

        <!--   <table class="workTable" v-loading="listLoading">
          <tr class="workTableTr">
            <td class="tdFixed" style="width:25px">序号</td>
            <td class="tdFixed" style="margin-left:40px;">姓名</td>
            <td v-for="(item,index) in dataList[0].work">
              <div :class="index==0?'maL':''">
                <span class="disblock" style="font-size:10px">
                  {{item.day}}
                </span>
                <br>
                <span class="disblock" style="font-size:10px">
                  {{formatDay(item.value)}}
                </span>
              </div>
            </td>
            <td>
              <div style="width:82px;"></div>
            </td>
            <td class="tdFixed2">操作</td>
          </tr>
          <tr v-for="(item,index ) in dataList">
            <td class="tdFixed" style="width:25px">{{index+1}}</td>
            <td class="tdFixed" style="margin-left:40px;">{{item.name}}</td>
            <td v-for="(item2,index2) in dataList[index].work" class="colorCss">
              <div :class="index2==0?'maL':''">
                <span v-if="item2.type==1" style="background:green;" class="tabbg">上班</span>
                <span v-if="item2.type==2" style="background:red;" class="tabbg">休息</span>
                <span v-if="item2.type==3" style="background:yellow;color:#000;" class="tabbg">调休</span>
              </div>
            </td>
            <td>
              <div style="width:82px;"></div>
            </td>
            <td class="tdFixed2">
              <el-button type="primary" size="mini" @click="handleUpdate(item)">编辑</el-button>
            </td>
          </tr>
        </table> -->
      </div>
      <!--  <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />-->
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog title="设置问诊时间" :visible.sync="dialogFormVisible">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>问诊时间管理({{departmentTimeRange}})</span>
        </div>
        <div style="border: 1px solid #e5e5e5; border-radius: 15px; padding: 20px">
          <el-button type="primary" @click="addM">新增</el-button>
          <el-form label-width="160px">
            <div v-for="(item, index) in ItemArr" :key="index">
              <el-form-item :label="'问诊时间' + (index + 1)">
                <el-row :span="24">
                  <el-col :span="5">
                    <el-time-picker :picker-options="rangeStart" value-format="HH:mm" format="HH:mm"
                      v-model="item.value1" placeholder="请选择开始日期"></el-time-picker>
                  </el-col>
                  <el-col :span="1" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  ">--
                  </el-col>
                  <el-col :span="5">
                    <el-time-picker value-format="HH:mm" format="HH:mm" v-model="item.value2" placeholder="请选择结束日期"
                      :picker-options="{
                      selectableRange: `${item.value1 + ':00'}-23:59:59`,
                    }"></el-time-picker>
                  </el-col>
                  <el-col :span="2" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  ">问诊量
                  </el-col>
                  <el-col :span="4">
                    <el-input type="number" v-model="item.value3" placeholder="请输入"></el-input>
                  </el-col>

                  <!--  <el-col :span="2" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  ">单价
                  </el-col>
                  <el-col :span="2">
                    <el-input type="number" v-model="item.value4" placeholder="请输入"></el-input>
                  </el-col> -->
                  <el-col :span="2" style="margin-left: 20px;">
                    <el-button type="danger" @click="deleM">删除</el-button>
                  </el-col>

                  <!--     <el-col :span="2" style="margin-left: 20px;">
                    <el-button type="danger" @click="deleM">删除</el-button>
                  </el-col> -->
                </el-row>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <ImportData @refresh="getDoctorScheduleList" ref="importData" />
  </div>
</template>

<script>
import { ApiDoctorScheduleList, ApiSubDepartment, ApiDoctorScheduleCreate, ApiDoctorScheduleDetail } from "@/api/index"
import ImportData from "./importData.vue";
/* import { listWork, createWork, updateWork, deleteWork } from "@/api/work"; */
/* import { getToken } from "@/utils/auth"; */
/* import Pagination from "@/components/Pagination";  */// Secondary package based on el-pagination
/* import vueCalendar from "@/components/vueCalendar.vue";//日历 */
/* import { Loading } from "element-ui"; */
export default {
  name: "Work",
  components: { ImportData },
  data() {
    return {
      //时间范围
      departmentTimeRange: "",
      ItemArr: [{ value1: "", value2: "", value3: "", }],
      subDepartMentArr: [],
      ordersList: [],
      monthData: [],
      formInline: {},
      cellClickForm: {},
      tableLoading: false,
      indexData: 0,
      rangeStart: {
        selectableRange: ('10:30:00 - 20:30:00'), // 10:30:00到20:30:00 的时间才可以选择
      },


      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        storeId: ''
      },
      dataForm: {
        id: undefined,
        mobile: undefined,
        password: undefined
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加"
      },
      isDisabled: false,
      storeId: "",
      isReturnBtn: false,

      value2: '',
      //type 1上班 2休息 3调休 
      dataList: [{
        name: '张三', nameId: 1, '2024-11-26': 11, schedule: [
          { day: '星期二', date: '2024-11-26', type: '0' },
        ]
      },
      {
        name: '李四', nameId: 2, schedule: [
          { day: '星期二', date: '2024-11-25', type: '1' },
        ]
      },
      ],
      dialogVisiblex: false,
      dataList2: [{ name: '小刘', nameId: 1, type: '2' }, { name: '小李', nameId: 2, type: '2' }, { name: '小王', nameId: 3, type: '2' }],
      tableRadio: ''
    };
  },
  props: {
    //门店ID
    receivingOrdersId: {
      type: '',
      default: null
    },
  },
  /*   computed: {
      headers() {
        return {
          accessToken: getToken()
        };
      }
    }, */
  created() {
    this.getCurrentMonth()
    this.getDoctorScheduleList()
    /*  this.getMonthData() */
    this.getSubDepartMent()

    /*  if (this.receivingOrdersId) { //有父级页面
       this.storeId = this.receivingOrdersId
       this.isReturnBtn = true
     } else {//没父级页面 门店账号登录
       this.storeId = this.$store.getters.storeId
       this.isReturnBtn = false
     }
     console.log('storeId', this.storeId)
     this.getDay() */
    /*     this.getList(); */
  },
  methods: {

    importData() {
      this.$refs.importData.show();
    },

    //获取当前月份
    getCurrentMonth() {
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从 0 开始的，所以需要加 1，并确保两位数
      let val = `${year}-${month}`;
      this.$nextTick(() => {
        this.$set(this.formInline, 'date', val);
      })
      this.getDaysInMonth(val)
      /*   this.formInline.date = val */

    },


    handleChangeData(e) {
      this.getDaysInMonth(e)
    },

    // 添加时间
    addM() {
      this.ItemArr.push({
        value1: "",
        value2: "",
        value3: "",
      });
    },
    // 删除时间
    deleM() {
      this.ItemArr.pop({
        value1: "",
        value2: "",
        value3: "",
      });
      /*  if (this.ItemArr.length > 1) {
         
       } else {
         this.$alert("最后一个无法删除！", "提示信息", {
           confirmButtonText: "确定",
         });
       } */
    },
    //拿到科室的数据
    getSubDepartMent() {
      ApiSubDepartment({ page: 1, size: 999 }).then(res => {
        this.subDepartMentArr = res.data
      })
    },






    //拿到当月的全部数据
    /*     getMonthData() {
          const today = new Date();
          const currentYear = today.getFullYear();
          const currentMonth = today.getMonth();
          const firstDayOfMonth = new Date(currentYear, currentMonth, 1);
          const lastDayOfMonth = new Date(currentYear, currentMonth + 1, 0);
          const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
          const monthData = [];
          for (let d = firstDayOfMonth; d <= lastDayOfMonth; d.setDate(d.getDate() + 1)) {
            const dayOfWeek = daysOfWeek[d.getDay()];  // 获取星期几
            const dateStr = d.toISOString().split('T')[0];  // 格式化为 YYYY-MM-DD
            monthData.push({
              day: dayOfWeek,
              date: dateStr,
              type: '0'
            });
          }
    
          this.monthData = monthData
        },
     */

    /*  getDaysInMonth(month) {
       console.log(month)
 
       if (month) {
         this.monthData = []
         const days = [];
         const [year, monthIndex] = month.split('-').map(Number); // 提取年份和月份
         const firstDayOfMonth = new Date(year, monthIndex - 1, 1); // 月份从0开始，所以减1
         const lastDayOfMonth = new Date(year, monthIndex, 0); // 获取该月的最后一天
 
         for (let i = 1; i <= lastDayOfMonth.getDate(); i++) {
           const date = new Date(year, monthIndex - 1, i + 1);
 
           const weekday = date.getDay(); // 获取星期几 (0-6)
 
           const weekNames = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
           const dayOfWeek = weekNames[weekday];
 
           const formattedDate = date.toISOString().split('T')[0]; // 格式化日期为 YYYY-MM-DD
 
           days.push({
             day: dayOfWeek,
             date: formattedDate,
             type: '0', // 可以根据需求调整
           });
         }
         this.monthData = days
         this.indexData++
       }
 
     }, */

    getDaysInMonth(month) {
      // 解析年月
      const [year, monthIndex] = month.split('-').map(num => Number(num));

      // 获取该月第一天和最后一天
      const firstDay = new Date(year, monthIndex - 1, 2);
      const lastDay = new Date(year, monthIndex, 1); // 获取最后一天

      /*    console.log('firstDay', firstDay, lastDay) */



      const dates = [];

      // 遍历每一天
      for (let day = firstDay; day <= lastDay; day.setDate(day.getDate() + 1)) {
        // 获取星期几
        const weekDays = ['星期六', '星期日', '星期一', '星期二', '星期三', '星期四', '星期五'];
        const dayOfWeek = weekDays[day.getDay()];

        // 格式化日期
        const formattedDate = day.toISOString().split('T')[0]; // 获取格式为 'YYYY-MM-DD'

        // 添加到结果数组
        dates.push({
          day: dayOfWeek,
          date: formattedDate,
          type: '0'
        });
      }

      this.monthData = dates
      this.indexData++
    },




    //拿到医生列表数据
    getDoctorScheduleList() {
      this.tableLoading = true
      ApiDoctorScheduleList(this.formInline).then(res => {

        if (res.data.departmentTimeRange) {
          this.departmentTimeRange = res.data.departmentTimeRange
          let val = res.data.departmentTimeRange.split('-')
          this.rangeStart.selectableRange = `${val[0]}:00 - ${val[1]}:00`
        }

        res.data.list.forEach(item => {
          if (item.schedule.length > 0) {
            item.schedule.forEach(i => {
              item[i.date] = i
            })
            item.type = '1'
          } else {
            item.type = '0'
          }

        })

        console.log('res.data.listres.data.listres.data.list', res.data.list)
        this.dataList = res.data.list
      }).finally(() => {
        this.tableLoading = false
      })
    },


    /*   JSON.parse(val).forEach(item => {
        arr.push(item.value1 + '-' + item.value2)
      }) */



    forMatterDate(val) {
      if (val) {
        return '问诊'
      }
    },
    //单元格进行点击的时候
    handleCellClick(row, column, cell, event) {
      this.dialogFormVisible = true
      this.ItemArr = [{ value1: "", value2: "", value3: "" }]
      console.log('rowrowrowrow', row)
      let that = this
      let arr = []
      ApiDoctorScheduleDetail({ doctor_id: row.id, date: column.property }).then(res => {
        res.data.list.forEach(item => {
          if (item.schedule) {
            let data = item.schedule.split('-')
            arr.push({ value1: data[0], value2: data[1], value3: item.schedule_number })
            that.ItemArr = arr
          }
        })
      }),

        this.cellClickForm = { doctor_id: row.id.toString(), date: column.property }
      /*    //点击对应的识别字段
         row.schedule.forEach(item => {
           if (item.date == column.property) {
             this.ItemArr = JSON.parse(item.schedule)
           }
         })
         this.cellClickForm = row
         this.cellClickForm = { doctor_id: row.id.toString(), date: column.property } */
    },





    updateData() {
      let arr = []
      this.ItemArr.forEach(item => {
        arr.push({ schedule: item.value1 + '-' + item.value2, schedule_number: item.value3 })
      })
      this.cellClickForm.list = arr
      ApiDoctorScheduleCreate(this.cellClickForm).then(res => {
        if (res.code == 200) {
          this.$message.success("提交成功");
          this.ItemArr = [{ value1: "", value2: "", value3: "" }]
          this.dialogFormVisible = false
          this.getDoctorScheduleList()
        }
      })
    },





    formatDay(value) {
      if (value) {
        return value.replace(/-/g, '/')
      }

    },
    /*    getDay() {
         const now = new Date()
         const year = now.getFullYear()  //年
         const month = now.getMonth() + 1 //月
         const day = now.getDate()    //日
         this.value2 = year + '-' + month
       }, */
    getList() {
      this.listLoading = true;
      this.listQuery.storeId = this.storeId//门店ID
      if (this.listQuery.startTime) {
        let startTime = this.listQuery.startTime.slice(0, 10) + ' 00:00:00'
        this.listQuery.startTime = startTime;

      }
      if (this.listQuery.endTime) {
        let endTime = this.listQuery.endTime.slice(0, 10) + ' 23:59:59'
        this.listQuery.endTime = endTime;

      }
      listWork(this.listQuery)
        .then(response => {
          this.ordersList = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.ordersList = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    //重置
    cancelList() {
      this.listQuery = {};
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = 20;
      this.getList();
    },
    handleFilter() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined
      };
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.dataForm.storeId = this.storeId
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.isDisabled = true
          createWork(this.dataForm)
            .then(response => {
              this.getList();
              this.dialogFormVisible = false;
              this.isDisabled = false
              this.$notify.success({
                title: "成功",
                message: "添加成功"
              });
            })
            .catch(response => {
              this.isDisabled = false
              this.$notify.error({
                title: "失败",
                message: response.data.msg
              });
            });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    //点击日历返回
    getwork(type, date) {
      if (type) {
        this.dataForm.day = date.value
        this.dataForm.type = date.type
        this.dialogVisiblex = true
      }

    },
    handleSelectionChange() {

    },
    cancel() {
      this.dialogVisiblex = false
    },
    getValue() {
      this.$forceUpdate()
    },
    goStoreList() {
      this.$emit("goStoreList");
    }
  }
};
</script>
<style>
.workTable {
  border-collapse: collapse;
  color: #606266;
  font-size: 14px;
  width: 100%;
  overflow: auto;
  display: inline-block;
  position: relative;
}
.workTable td {
  border: 1px solid #ebeef5;
  padding: 8px;
  text-align: center;
}
.colorCss {
  padding: 0px !important;
  color: #fff;
}
.tabbg {
  width: 100%;
  display: inline-block;
  line-height: 48px;
}
.workTableTr {
  width: 100%;
  color: #909399;
  font-weight: bold;
}

.nowrapTab {
  overflow: auto;
  white-space: nowrap;
}
.workTabtd {
  display: inline-block;
  width: 100px;
}
.disblock {
  display: inline-block;
}
.tdFixed {
  position: fixed;
  display: flex;
  background: #fff;
  height: 50px;
  width: 100px;
  justify-content: center;
  align-items: center;
}
.maL {
  margin-left: 150px;
}
.tdFixed2 {
  position: fixed;
  display: flex;
  background: #fff;
  height: 50px;
  width: 100px;
  justify-content: center;
  align-items: center;
  right: 30px;
}
.tbCss div {
  padding-left: 10px;
}
</style>

